<html>
<div id="loading">
<img src=images/loading.gif> <font color=#008080 size=3><b> Please wait a second ...</b></font>
</div>
<script>
function hideLoading()
{
  var disp = document.getElementById('loading');
  disp.innerHTML = '';
}

</script>

<body>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';
include 'head.htm';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$_SESSION['tab'] = 0;
$act = getHttpVal('act', 'findkey');
$start = getHttpVal('start', 0);
$id=getHttpVal('id',-1);
//echo 'act='.$act.', id='.getHttpVal('id',-1).', counter='.getHttpVal('counter',-1);

if (strcmp($act,'Update')==0 && $id > 0) {

  writeLog("ListUsers::Main Update call", true);
  $notes = getHttpVal('notes', '');
  $active = getHttpVal('status', 1);
  $grp = getHttpVal('group', 1);
  $type = getHttpVal('type', 1);
  $client_id = getHttpVal('clientId', -1);
  date_default_timezone_set('UTC');
  $dt2=date("Y-m-d H:i:s");
  
  $stmt = 'UPDATE users SET notes='.mysql_quote($notes).
    ', group_id='.getGroupId(trim($grp)).', user_status='.$active.', user_type='.mysql_quote($type).
    ', accessed='.mysql_quote($dt2);
    
  if (isRootAdm() && $client >= 0) {
    $stmt .= ', client_id='.$client_id;
  }
  $stmt .= ' WHERE user_id='.$id;
  if ($r = query($stmt)) {
    $_SESSION['alert'] = 'User-'.$id.' was updated successfully';
  } else {
    $_SESSION['alert'] = 'User update failed! '.$contactAdm;
  }
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
} elseif (strcmp($act,'Delete')==0 && $id > 0) {

  writeLog("ListUsers::Main Delete call", true);

  $user = getHttpVal('user', '');
  $clientId = getHttpVal('clientId', '');
  
  if (($n=numOfMapYubikeys($id, -1)) > 0) {
	  	$_SESSION['alert'] = 'User-'.$user.' still has '.$n.' maped Yubikeys! Re-assign or delete the provision first.';
	} else {
	  if (delUser($id, $clientId)) {
		$_SESSION['alert'] = 'User-'.$user.' deleted successfully';
	  } else {
		$_SESSION['alert'] = 'Failed to delete User-'.$user.'! '.$contactAdm;
	  } 
	}
	
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

}elseif (strcmp($act,'Add')==0) {

  writeLog("ListUsers::Main Add called", true);

  $userName = getHttpVal('uName', '');
  $clientId = getHttpVal('uClient', 1);
  $loginName = getHttpVal('lName', '');
  $userType = getHttpVal('uType', '');
  $group = getHttpVal('uGroup', '');
  $userNotes = getHttpVal('uNotes', '');
  $dt2=date("Y-m-d H:i:s");
  
  $stmt = 'INSERT INTO users(client_id, user_status, group_id, user_name, user_type, login_name, notes, created, accessed)'.
    'VALUES ('.$clientId.', 1, '.getGroupId(trim($group)).', '.mysql_quote($userName).', '.mysql_quote($userType).', '.mysql_quote(trim($loginName)).
    ', '.mysql_quote($userNotes).', '.mysql_quote($dt2).', '.mysql_quote($dt2).')';
  
  writeLog("ListUsers::Main Add Qry".$stmt, true);
  if ($r = query($stmt)) {
    $_SESSION['alert'] = 'User-'.$userName.' is added successfully';
  } else {
    $_SESSION['alert'] = 'User add failed! '.$contactAdm;
  }  

  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

} else {
  writeLog("ListUsers::Main selecting call ".$$act, true);  
  if (strcmp($act,'Retrieve')==0) {
  	
    writeLog("ListUsers::Main Retrieve call", true);
    $id_type = getHttpVal('idtype', '');
    $searchtxt = getHttpVal('searchtxt', 1);
    
    $act = 'findkey';
    $attrName=getHttpVal('attr_name', $id_type);
    $attrVal=getHttpVal('attr_val', $searchtxt);    
    
    //idtype, searchtxt
  }
}

if (showMyUsers($act, $start, $attrName, $attrVal) == 0) {
    echo '<h4>No Users!</h4>';
}

// If client id = 0, meaning it's the root user, display all clients
function displayUser($row, $toggle) {
  
  $client = $row['client_id'];
  $uid = $row['user_id'];

  echo '<tr'.($toggle ? ' bgcolor=#eeeeee>' : '>');
  echo '<form method=POST action=list_users.php>'.
    '<input name=act type=hidden value=upd_key>'.
    '<input name=clientId type=hidden value='.$client.'>'.
    '<input name=id type=hidden value='.$uid.'>'.
    '<input name=user type=hidden value='.$row['user_name'].'>'.
    '<td align=center valign=center><font size=2>';
  
  /*
  if ($keyId == $_SESSION['keyid']) {
  	echo '<img src=images/yubiright_16x16.gif title="This is the admin Yubikey you are using to log in!"><p>';
  } else if (isAdmKey($keyId)) {
  	echo '<img src=images/admkey.gif title="This is an admin Yubikey"><p>';
  }*/
  
  echo  $row['user_name'].'</td>'; /// UserName
  // needed in Admin view
  if (isRootAdm()) {
    echo '<td nowrap align=center><font size=1>'.
  	makePopupURL('edit_client.php?client='.$client,$client,500,'#BB0000','Client Info').		
  	'</td>';
  }

  
  writeLog("ListUsers::displayUser LoginName = ".$row['login_name'] , true);
  echo  '<td align=center valign=center><font size=2>'.$row['login_name'].'</td>'; /// UserName

    ///  User Status
  echo '<td align=center valign=center><font size=2>';
  echo '<select name=status>';
  echo '<option value="0" '.($row['user_status']==0 ? 'selected' : '').'>Inactive'.
  	 '<option value="1" '.($row['user_status']==1 ? 'selected' : '').'>Active';
  echo '</select>';
  echo '</td>';

    ///  User Type
  echo '<td align=center valign=center><font size=2>';
  echo '<select name=type>';
  echo '<option value="admin" '.($row['user_type']=="admin" ? 'selected' : '').'>Admin'.
  	 '<option value="user" '.($row['user_type']=="user" ? 'selected' : '').'>User';
  echo '</select>';
  echo '</td>';

    ///  User Group
  echo '<td align=center valign=center><input type="text" name=group id=group value="'.getGroupName($row['group_id']).'"></imput></td>';
  /*
  echo '<td align=center valign=center><font size=2>';
  echo '<select name=group>';
  echo '<option value="0" '.($row['group_id']==0 ? 'selected' : '').'>Admin'.
  	 '<option value="1" '.($row['group_id']==1 ? 'selected' : '').'>Demo';
  echo '</select>';
  echo '</td>';
  */
  
  echo '<td align=center valign=center><textarea name=notes cols=10 rows=2 class=inputtxt>'.$row['notes'].'</textarea></td>';
  echo '<td align=center valign=center><input name=act type=submit value=Update class=buttonLinkSmall>&nbsp;'.
  	 '<input name=act type=submit value=Delete class=buttonLinkSmall></form></td></tr>';
  	
} // End displayUser

// $act: operation code = findkey | list_keys
// $otp: modhex OTP from a Yubikey
function showMyUsers($act, $start, $attrName, $attrVal) {
  $client = $_SESSION['client'];
  //echo 'act='.$act.', attrName='.$attrName.', val='.$attrVal;
  $stmt = 'select u.user_id, u.client_id, u.user_status, u.group_id, u.user_name, u.user_type, u.login_name'.
		' ,u.notes FROM users u ';
  
  if ($act == 'findkey') {
	if (isRootAdm() && $attrName=='client_id' && is_numeric($attrVal)) { // adm can see keys of any client
  		$stmt .= 'WHERE client_id='.$attrVal; /// need to think about it
  	} else if ($attrName=='userName') {
  		$stmt .= 'WHERE user_name='.mysql_quote($attrVal);
	} else if ($attrName=='loginName') {
  		$stmt .= 'WHERE login_name='.mysql_quote($attrVal);
	} else {
  		$act = 'list_keys';
  	}
  } else {
  	$act = 'list_keys';
  }

  if (!isRootAdm()) { // If not root, can only see your own Yubikeys
   	if (strpos($stmt, 'WHERE') === false) { 
  		$stmt .= ' WHERE '; 
  	} else {
  		$stmt .= ' AND ';
  	}
  	$stmt .= ' client_id='.$client;
  }
  
  $stmt .= ' LIMIT ' . $start . ', ' . MAX_PER_PAGE;
  
  writeLog($stmt, true);
  
  echo '<table border=0 width=100%><tr><td valign=top colspan=9 align=left><font size=2>';
  
  if (isRootAdm()) {
    if ($attrName == 'client_id') {
    	echo makePopupURL('edit_client.php?client='.$attrVal,'Client-'.$attrVal,500,'#BB0000','Client Info').
		  ' has '.numOfYubikeys($attrVal,1).' active Yubikeys, '.
    	  numOfYubikeys($attrVal,0).' inactive Yubikeys.';
    } else {
		echo 'There are '.numOfUsers(-1,1).' active Yubikeys, '.numOfUsers(-1,0).
			' inactive Yubikeys.';
    }
  } else {
    $a = getClientUserInfo($client);
  	echo 'You have '.$a['num_active'].' active Users, '.$a['num_inactive'].' inactive Users.';
  }
  funcBar($act, $attrName, $attrVal);
  echo '</td></tr><tr><td height=8></td></tr>';
   
  ////// Find matching yubikeys
  //   
  //if (strlen($attrVal) < 1) { return 1; }
  $r = query($stmt);
  $n=mysql_num_rows($r);
  writeLog("ListUsers::showMyUsers Row Count = ".$n , true);  	
  
  /// Col. Headers
  $title = '<tr bgcolor=#ADFF2F><th><font size=1>User Name</th>';
  if (isRootAdm()) {
	$title .= '<th><font size=1>Client</th>';
  }
  $title .= '<th><font size=1>Login Name</th><th><font size=1>Status</th><th><font size=1>User Type</th><th><font size=1>Group</th>';
  $title .= '<th><font size=1>Note</th><th></th></tr>'; // not need (req. Testing)
  
  echo $title;
  /// Col. Headers End
  
  $i=0;
  while ($row=mysql_fetch_assoc($r)) {  
	displayUser($row, $i % 2);
//	print_r($row);
	if (++$i % 21 == 0) {
		echo $title;
	}
  }
  
  mysql_free_result($r);
  echo '</table>';
  
  echo '<br><font color=#008080 size=2><b>Showing ' . $i . ' record(s)</b></font><br><br>';
  
  if ($i < MAX_PER_PAGE) {
  	return ($i > 0 ? $i : -1);
  }
  
  echo '<h3><a href=#top>^ TOP</a><center><a name=BOT></a>';
  
  if ($attrName =='client_id') {
  	$filter = '&act=findkey&attr_name=client_id&attr_val='.$attrVal;
  } else {
  	$filter ='';
  }
  
  if ($start > 0) {
  	if (($s = $start - MAX_PER_PAGE) < 0) { $s = 0; }  	
  	echo '<a href=list_users.php?act=list_keys&start='.$s.$filter.'>PREV</a> | ';
  }

  if ($i >= MAX_PER_PAGE-1) {  	
  	echo '<a href=list_users.php?act=list_keys&start='.($start+MAX_PER_PAGE).$filter.'>NEXT</a>';
  }
  
  echo '</h3></center>';
  
//  echo '<table><tr><td valign=top><img src=images/arrow.jpg></td>'.
//     '<td nowrap valign=bottom><a href=#DOWN onclick="javascript:showAddUser(0,'.$client.');">'.
//     '<b><font color=#008080 size=2><b> Add a User >></b></font></a>'.
//     '<p><div id=impkey></div></td></tr></table>';
    
  return $n;

} // End showMyAccts

// op = list_keys, findkey
function funcBar($act, $attrName) {
	global $page;
	
    echo '<hr size=1><table><tr><td valign=top><img src=images/arrow.jpg></td>'.
      '<td nowrap valign=bottom><a href=#DOWN onclick="javascript:showAddUser(0,'.$_SESSION['client'].');">'.
      '<b><font color=#008080 size=2><b> Add a user >></b></font></a>'.
      '<p><div id=impkey></div></td></tr></table>';
    	
	echo '<table border=0 width=80%>'.
	  '<tr><td colspan=9 height=10></td></tr>';

    echo '<tr>';

	if ('list_keys' != $act) {
    	echo '<tr><td valign=top> ';
    	divBut(150, $page.'?act=list_keys','<font size=2>>> List All Users</font>');
    	echo '</td><td width=10></td><td width=30 nowrap valign=top>&nbsp;or&nbsp;</td>';
	}

    echo '<tr><td colspan=9 align=left><hr size=1>'.     
      '<form autocomplete=off method=POST action=list_users.php>'.
	  '<table border=0 width=90%>'.
	  '<tr><td colspan=9 align=center><font color=#008080 size=2><b>'.
	   'List of the users associated with the Client:</b><br><br>'.
	  '</td></tr>'.
	  '<tr><td valign=top>' .
	  '<font size=2 color=#AA0000><p>'.
	  	'» Choose a Search type (user/login name ):<br>'.
		'<select id=idtype name=idtype>'.
	    '<option value=userName>User Name'.
		'<option value=loginName>Login Name'.
	    '</select></td>'.
	    '<td align=left>»</td>'.
		'<td><font size=2 color=#AA0000>Enter the search text:</font><br>'.
		'<textarea name=searchtxt id=searchtxt rows=1 cols=37"></textarea><p>'.
	  '</td><td>»</td><td>' .
	  '<input name=act type=submit value=Retrieve class=buttonLinkSmall>'.	  
	  '</td></tr></table>'.
	  '</form>'.
	  '</td></tr>';  	
  	
	echo '</table><hr size=1>';
}

?>

<script>
hideLoading();
</script>
</body>
</html>
